package com.c.ctgproject.ui.collect

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.guang.MaterialCheckInputAdapter
import com.c.ctgproject.adapter.guang.MaterialChildSelectAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityMaterialWarehouseOutSubmitBinding
import com.c.ctgproject.entity.guang.*
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.common.ListSelectDialog
import org.jetbrains.anko.startActivity

/**
 *作者:LiBW
 *创建日期: 2021/9/18
 *描述: 新建出库计划 页面
 */
class MaterialWarehouseOutSubmitActivity : BaseActivityV2(), MaterialCheckInputAdapter.TestListener, MaterialChildSelectAdapter.MaterialChildSelectAdapter {
    private val mBinding by lazy { ActivityMaterialWarehouseOutSubmitBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root
    private val mList = ArrayList<MaterialOutSubmitBean>()

    private val mMartialList = ArrayList<MaterialChildListEntity.DataBean>()
    private var mDialog: ListSelectDialog? = null
    private val mAdapter by lazy { MaterialCheckInputAdapter(this, mList, this) }

    //出库类型 出库类型 1-销售出库 2-借用出库 3-其他出库
    private var outType = 1

    //客户
    private var customerName = ""

    //审批人
    private var auditPersonName = ""
    private var auditPersonId = -1

    //旧数据 有就是继续提交
    private val outOrderId by lazy { intent.getIntExtra(MyConstants.ID, -1) }

    //是否为草稿 如果有旧数据 而且不是草稿 那么就是驳回的重新申请
    private val isDraft by lazy { intent.getBooleanExtra(MyConstants.Draft, false) }

    //我的里面 待审核的可以再次编辑
    private val isUpdate by lazy { intent.getBooleanExtra(MyConstants.UPDATE, false) }

    override fun event() {
        //是草稿或者驳回的重新提交
        if (outOrderId != -1) {
            handlerOldData()
            mBinding.mTitleBar.setTitle("编辑出库计划")
            mBinding.mMineTV.visibility = View.GONE
            if (isDraft) {
                //支持删除草稿
                mBinding.mDeleteDraftTV.visibility = View.VISIBLE
            }
            if (isUpdate) {
                //我的里面过来在编辑的不能提交草稿单
                mBinding.mDraftBTN.visibility = View.GONE
            }
        }
        mList.add(MaterialOutSubmitBean())
        mBinding.mRecyclerView.adapter = mAdapter
        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)

//        ApiMethods.apiSubscribe(ApiMethods.retrofit.materialChildList(), MyObserverHandlerLoading(this, loading) {
//            MyLog.d("物料列表回调:$it")
//            val data = getGson().fromJson(it, MaterialChildListEntity::class.java).data
//            data?.let { list ->
//                mMartialList.addAll(list)
//                val adapter = MaterialChildSelectAdapter(this, mMartialList, this)
//                mDialog = ListSelectDialog("物料选择", adapter, true)
//            }
//        })
    }


    override fun click() {
        //我的
        mBinding.mMineTV.setOnClickListener {
            startActivity<MaterialMyCreateOutActivity>()
        }
        //审批人
        mBinding.mCheckerLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.CHECK_USER.menuCode, true, arrayListOf(auditPersonName), resultCode = 104, partFrom = 4, canInput = false)

        }

        //选择客户名称
        mBinding.mDictionarySelectLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.CUSTOMER.menuCode, true, arrayListOf(customerName))
        }

        mBinding.mXS.setOnClickListener { outType = 1 }
        mBinding.mJY.setOnClickListener { outType = 2 }
        mBinding.mQT.setOnClickListener { outType = 3 }


        mBinding.mAddPartTV.setOnClickListener {
            mList.add(MaterialOutSubmitBean())
            mAdapter.notifyDataSetChanged()
//            mAdapter.notifyItemInserted(mList.size - 1)
        }

        //存为草稿
        mBinding.mDraftBTN.setOnClickListener {
            checkData(0)
        }

        //提交
        mBinding.mConfirmBTN.setOnClickListener {
            checkData(1)
        }

    }

    //0为草稿 1为提交
    private fun checkData(submit: Int) {
        var canSubmit = true
        mList.forEach {
            if (it.materialCode.isEmpty() || it.materialName.isEmpty() || it.count.isEmpty()
            ) {
                canSubmit = false
                return@forEach
            }
        }
        when {
            submit == 1 && customerName.isEmpty() -> {
                showToast("请选择客户")
                mBinding.mDictionarySelectLL.myShake()
            }
            submit == 1 && auditPersonName.isEmpty() -> {
                showToast("请选择审批人")
                mBinding.mCheckerLL.myShake()
            }
            submit == 1 && !canSubmit -> {
                showToast("请填写完整数据")
                mBinding.mRecyclerView.myShake()
            }
            else -> {
                submit(submit)
            }
        }
    }

    //submit 0草稿 1提交
    private fun submit(submit: Int) {
        val map = HashMap<String, Any>()
//        map["stockId"] = id

        if (!isDraft) {
            //不是草稿就告诉他我要提交还是草稿
            map["status"] = submit
        }

        if (outOrderId != -1) {
            map["outOrderId"] = outOrderId
        }

        //出库类型 【1-销售出库 2-借用出库 3-其他出库】
        map["outType"] = outType
        //出库方式 【1-电池 2-零件 3-物料】 app只有3
        map["outMethod"] = 3
        map["customer"] = customerName
        map["auditPersonName"] = auditPersonName
        map["auditPersonId"] = auditPersonId
        map["remark"] = mBinding.mRemarkET.text.handlerNull()
        map["materialItems"] = mList
        //新建状态，默认为草稿状态 【0-草稿 1-待审核】
        if (isDraft && submit == 0) {
            //草稿单重新提交草稿
            ApiMethods.apiSubscribe(ApiMethods.retrofit.materialDraftUpdate(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                MyLog.d("回调:$it")
                showToast("提交成功")
                finish()
            })

        } else {
            if (outOrderId != -1) {
                if (isUpdate) {
                    //待审核的单子修改了重新提交
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.materialOutSecondUpdate(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                } else {
                    //如果有旧ID说明是草稿单二次提交或者驳回单子二次提交
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.materialOutSecond(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                }
            } else {
                //重新搞了一个接口如果是提交就提交 草稿掉新接口(去除了验证)
                if (submit == 1) {
                    //新单子提交审批或者提交草稿
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.materialOutSubmitV2(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                } else {
                    //存草稿
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.materialOutSubmitToDraft(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                }
            }
        }
    }


    override fun onRemoveClick(position: Int) {
        if (mList.size == 1) {
            showToast("请至少填写一条数据")
        } else {
            mList.removeAt(position)
            mAdapter.notifyDataSetChanged()
//            mAdapter.notifyItemRemoved(position)
        }
    }

    //去选择一个物料吧
    override fun onSelectMaterialSelect(position: Int) {
        currentPosition = position
        MyLog.d("选一个物料吧")
        //TODO 配件
        DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.PARTS.menuCode, true, arrayListOf(mList[position].materialName), canInput = false, resultCode = 100, partFrom = 3)


//        mDialog?.let {
//            if (!it.isAdded) {
//                it.show(supportFragmentManager, "")
//            }
//        }
    }

    override fun onNumberChange(number: String, position: Int) {
        mList[position].count = number
    }

    override fun onUnitChange(unit: String, position: Int) {
//        mList[position].unit = unit
    }

    private var currentPosition = -1

    //物料选中了什么
    override fun onItemClick(position: Int) {
        mList[currentPosition].materialCode = mMartialList[position].materialCode
        mList[currentPosition].materialName = mMartialList[position].materialName
        mAdapter.notifyItemChanged(currentPosition)
        mDialog?.dismiss()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            //字典回调

            when (requestCode) {
                1000 -> {
                    val name = result.getStringExtra(MyConstants.NAME)
                    customerName = name.handlerNull()
                    mBinding.customer.text = name.handlerNull()
                }
                100 -> {
                    val name = result.getStringExtra(MyConstants.NAME).handlerNull()
                    val code = result.getStringExtra(MyConstants.ABBREVIATION).handlerNull()
                    mList[currentPosition].materialCode = code
                    mList[currentPosition].materialName = name
                    mAdapter.notifyItemChanged(currentPosition)
                }
                104 -> {
                    //审批人员回调
                    val name = result.getStringExtra(MyConstants.NAME).handlerNull()
                    val abbreviation = result.getStringExtra(MyConstants.ABBREVIATION).handlerNull()
                    auditPersonName = name
                    auditPersonId = abbreviation.toInt()
                    mBinding.mCheckerTV.text = name
                }
            }
        }
    }

    //处理旧数据
    private fun handlerOldData() {
        ApiMethods.apiSubscribe(ApiMethods.retrofit.outMaterialDetail(outOrderId), MyObserverHandlerLoading(this, loading) {
            MyLog.d("放行条详情回调回调回调:$it")
            MyLog.d("详情回调:$it")
            val data = getGson().fromJson(it, MaterialOutCheckDetailEntity::class.java).data
            data?.let { bean ->
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "出库单号", bean.bizNo.noDataHandler()))
//                val outType = when (bean.outType) {
//                    1 -> "销售出库"
//                    2 -> "借用出库"
//                    3 -> "其他出库"
//                    else -> "暂无数据"
//                }
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "出库类型", outType))
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "客户", bean.customer.noDataHandler()))
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "开单人", bean.createPersonName.noDataHandler()))
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "开单时间", bean.createTime.noDataHandler()))
//                mBinding.mContainerLL.addView(CarInfoLayout(this, "备注", bean.remark.noDataHandler()))


                bean.outType?.let {
                    outType = it
                }
                when (bean.outType) {
                    1 -> mBinding.mXS.performClick()
                    2 -> mBinding.mJY.performClick()
                    3 -> mBinding.mQT.performClick()
                }
                //审批人
                auditPersonName = bean.auditPersonName.handlerNull()
                bean.auditPersonId?.let {
                    auditPersonId = it
                }
                mBinding.customer.text = bean.customer.handlerNull()
                customerName = bean.customer.handlerNull()
                mBinding.mRemarkET.textSet(bean.remark.handlerNull())

                mBinding.mCheckerTV.text=auditPersonName
            }

            mList.clear()
            //出库物品明细
            data?.materialItems?.forEach { b ->
                val bean = MaterialOutSubmitBean()
                bean.materialCode = b.materialCode.handlerNull()
                bean.materialName = b.materialName.handlerNull()
                bean.count = b.count.handlerNull()
                mList.add(bean)
            }
            mAdapter.notifyDataSetChanged()
//            val data = getGson().fromJson(it, CheckDetailEntity::class.java).data
//            //获取attr图片
//            val imageUrls = ArrayList<String>()
//            data?.attachments?.forEach { bean ->
//                imageUrls.add(bean.attUrl.handlerNull())
//            }
//            if (imageUrls.isNotEmpty()) {
//                val resultList: MutableList<NineGridBean> = ArrayList()
//                imageUrls.forEach { bean ->
//                    val nineGirdData = NineGridBean(bean)
//                    imageShowList.add(bean)
//                    resultList.add(nineGirdData)
//                }
//                mBinding.mPhotoNGV.addDataList(resultList)
//            }
//
//            //放行条明细
//            mList.clear()
//            data?.releaseItems?.forEach { bean ->
//                val b = CheckPassDetailBean()
//                b.count = bean.count
//                b.name = bean.name.handlerNull()
//                b.name2 = bean.name2.handlerNull()
//                b.remark = bean.remark.handlerNull()
//                b.type = bean.type.handlerNull()
//                b.unit = bean.unit.handlerNull()
//                mList.add(b)
//            }
//            mAdapter.notifyDataSetChanged()
//
//            data?.let { bean ->
//                mBinding.mDepartment.text = bean.department.handlerNull()
//                department = bean.department.handlerNull()
//                mBinding.carryingEnterpriseTV.text = bean.carryingEnterprise.handlerNull()
//                carryingEnterprise = bean.carryingEnterprise.handlerNull()
//                mBinding.carrier.textSet(bean.carrier.handlerNull())
//                mBinding.carPlate.textSet(bean.plate.handlerNull())
//            }
//            handlerCount()
        })
    }
}